//
//  SchollSearchController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/5/3.
//  Copyright © 2016年 game. All rights reserved.
//

#import "SchollSearchController.h"
#import "SearchTakeView.h"
#import "SchoolSearchResultCtrl.h"
#import "MBButtonWithFontAdapter.h"
#import "MBLabelWithFontAdapter.h"
#import "MBTextFieldWithFontAdapter.h"
#import "MBTextViewWithFontAdapter.h"
@interface SchollSearchController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic,strong) NSMutableArray *serchAry;

/**
 *  写本地文件路径
 */
@property (nonatomic,copy) NSString *path;

@end

@implementation SchollSearchController

-(NSMutableArray *)serchAry{
    if (!_serchAry) {
        _serchAry = [NSMutableArray array];
    }
    return _serchAry;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    StatusBlack;
}

- (IBAction)CancelClick:(MBButtonWithFontAdapter *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  创建存文件的路径
 */
-(NSString *)CreatPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/IslanSearch",NSHomeDirectory()];;
    
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];//在路径创建文件夹
    NSString *filePath = [NSString stringWithFormat:@"%@/SchoolSearch.plist",path];
    return filePath;
}


/**
 *  textFile左边视图  放大镜
 */
-(UIView *)textFileLweftView{
    UIView *bacView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn-search-grey"]];
    imageView.frame = CGRectMake(8,5,W(bacView)-10,W(bacView)-10);
    [bacView addSubview:imageView];
    
    return bacView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = tabGropBackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.textField.leftView = [self textFileLweftView];
    self.textField.leftViewMode=UITextFieldViewModeAlways;
    
    self.textField.delegate = self;
    
    self.path = [self CreatPath];
    self.serchAry = [NSMutableArray arrayWithContentsOfFile:self.path];
    
    [self.textField becomeFirstResponder];
    
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [_tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.tableview.tableFooterView = [UIView new];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.serchAry.count==0) {
        tableView.alpha = 0;
    }else{
        tableView.alpha = 1;
    }
    return self.serchAry.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",self.serchAry[indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return SCREEN_HEIGHT *0.08;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    SearchTakeView *takeview = [[NSBundle mainBundle]loadNibNamed:@"SearchTakeView" owner:nil options:nil].lastObject;
    [takeview.clearBtn addTarget:self action:@selector(clearBtnAction) forControlEvents:UIControlEventTouchUpInside];
    return takeview;
}

-(void)clearBtnAction{
    [self.serchAry removeAllObjects];
    [self.tableview reloadData];
    [self.serchAry writeToFile:self.path atomically:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    [self MakeSearhAryWhithString:cell.textLabel.text];
}

#pragma mark - scrollview代理方法
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.textField endEditing:YES];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]) {
        
        [self MakeSearhAryWhithString:textField.text];
        
    }
    return YES;
}

/**
 *  操作数组  点击选择后 对数据进行更改 存档 并进行页面跳转
 */
-(void)MakeSearhAryWhithString:(NSString *)string{
    
    SchoolSearchResultCtrl *ctl=[[SchoolSearchResultCtrl alloc] init];
    ctl.searchString = string;
    [self.navigationController pushViewController:ctl animated:YES];
    
    if (self.serchAry.count==0) {
        [self.serchAry addObject:string];
    }
    
    NSInteger have = 1;
    NSInteger index =0 ;
    for (NSString *ssst in self.serchAry) {
        
        if ([ssst isEqualToString:string]) {
            have = 2;
            index = [self.serchAry indexOfObject:ssst];
        }
    }
    
    if (have==1) {
        [self.serchAry insertObject:string atIndex:0];
    }
    
    if (have==2) {
        [self.serchAry removeObjectAtIndex:index];
        [self.serchAry insertObject:string atIndex:0];
    }
    
    [self.serchAry writeToFile:self.path atomically:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableview reloadData];
    });
}
-(void)didReceiveMemoryWarning{
    
    [super didReceiveMemoryWarning];//即使没有显示在window上，也不会自动的将self.view释放。
    
    if ([self.view window] == nil) {
        
        self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        
    }
}

@end
